<template>
  <el-dialog :modelValue="props.typeDia.visible" title="编辑类型" width="30%" center
      :before-close="closeEditTypeDiaDialog" @open="dialogOpenHandler">
      <el-row>
          <el-col :span="24">
              <div class="edit-type-card" :style="`height:${250}px;overflow:auto`">
                  <el-form ref="typeFormRef" style="max-width: 600px" :model="typeForm" :rules="rules"
                      label-width="auto" class="" :size="'small'" status-icon>

                      <el-form-item label="类型名称" prop="name">
                          <el-input placeholder="请输入类型名称" v-model="typeForm.name" />
                      </el-form-item>

                      <el-form-item label="类型描述" prop="des">
                          <el-input v-model="typeForm.des" type="textarea" maxlength="500" placeholder="请输入类型描述"
                              show-word-limit rows="5" />
                      </el-form-item>

                      <!-- Subsystem Dropdown -->
                      <el-form-item label="所属子系统" prop="subsystemId">
                          <el-select v-model="typeForm.subsystemId" placeholder="请选择子系统">
                              <el-option
                                  v-for="subsystem in subsystems"
                                  :key="subsystem.id"
                                  :label="subsystem.name"
                                  :value="subsystem.id"
                              />
                          </el-select>
                      </el-form-item>

                  </el-form>
              </div>
          </el-col>
      </el-row>
      <template #footer>
          <el-form-item style="width: 100%;">
              <div style=" width: 100%; display: flex;justify-content: center;">
                  <el-button size="small" type="primary" @click="submitForm(typeFormRef)">
                      保存
                  </el-button>
                  <el-button size="small" @click="resetForm(typeFormRef)">取消</el-button>
              </div>
          </el-form-item>
      </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { defineComponent, reactive, ref, onMounted } from "vue";
import HttpService from "@/api/api";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

const props = defineProps({
  typeDia: Object // Contains visibility and data of the type to be edited
});

const emits = defineEmits(["dialogSubmit", "closeEditTypeDiaDialog"]);

const typeFormRef = ref<FormInstance>();
let typeForm = reactive({
  id: "", // ID to identify the type being edited
  name: "",
  des: "",
  subsystemId: "", // Add subsystemId to the form model
  parentId: ""
});

const subsystems = ref([]); // Subsystems list
const subsystemPagination = reactive({
  page_index: 1,
  page_size: 10,
  page_total: 0
});
const tableLoading = ref(false);

const rules = reactive<FormRules>({
  name: [
      { required: true, message: "请输入类型名称", trigger: "blur" },
      { min: 1, max: 50, message: "长度为1-50个字符", trigger: "blur" }
  ],
  des: [
      { required: false, message: "请输入类型描述", trigger: "blur" },
      { min: 1, max: 500, message: "长度为1-500个字符", trigger: "blur" }
  ],
  subsystemId: [
      { required: true, message: "请选择所属子系统", trigger: "change" }
  ]
});

// Fetch subsystems
const getSubsystems = () => {
  const params = {
      limit: subsystemPagination.page_size,
      page: subsystemPagination.page_index
  };
  tableLoading.value = true;
  HttpService.subsystemManage.subsystemList(
      params,
      (res) => {
          if (res.status === 200) {
              subsystems.value = res.data.data;
              subsystemPagination.page_total = res.data.total;
          } else {
              ElMessage.error("获取子系统列表失败");
          }
          tableLoading.value = false;
      },
      (error) => {
          ElMessage.error("请求失败，请稍后重试");
          tableLoading.value = false;
      }
  );
};

const dialogOpenHandler = () => {
  getSubsystems(); // Fetch subsystems when the dialog opens
  if (props.typeDia) {
      // Populate form with data to be edited
      typeForm.id = props.typeDia.id;
      typeForm.name = props.typeDia.name;
      typeForm.des = props.typeDia.des;
      typeForm.subsystemId = props.typeDia.subsystemId;
      typeForm.parentId = props.typeDia.parentId;
  }
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
      if (valid) {
          emits("dialogSubmit", typeForm); // Emit updated form data
          closeEditTypeDiaDialog();
      } else {
          console.log("error submit!", fields);
      }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  closeEditTypeDiaDialog();
};

const closeEditTypeDiaDialog = () => {
  emits("closeEditTypeDiaDialog");
};

onMounted(() => {
  getSubsystems();
});
</script>

<style lang="scss" scoped>
.edit-type-card {
  overflow: auto;
}
</style>
